<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #imageBox{
            position: relative;
        }
        #cutBox{
            width: 150px;
            height: 150px;
            border: 1px solid red;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>
<h1>头像上传</h1>
<input id="upload" type="file">
<div id="imageBox">
    <canvas id="myCanvas" width="500"height="500"style="border: 1px solid pink"></canvas>
    <div id="cutBox"></div>
</div>
<button id="uploadBtn">上传</button>
<div>
    <h1>预览</h1>
    <canvas id="newCanvas" width="200"height="200"style="border: 1px solid red"></canvas>
</div>
<img id="myimg" alt="">
<script src="js/jquery-1.11.3.js"></script>
<script>
    let ctx = $("#myCanvas")[0].getContext('2d')
    let newCtx = $('#newCanvas')[0].getContext('2d')
    //  1 预览选中的图片
    $('#upload').change(function () {
        // 1.1  获取选中的图片文件
        let imgFile = this.files[0]
        let reader = new FileReader()
        reader.readAsDataURL(imgFile)
        console.log(imgFile)
        reader.onload = function () {
            let img = document.createElement('img')
            img.src = this.result/*图片文件的beas64码*/
            img.onload = function () {
                ctx.drawImage(img,0,0,500,500)
            }
        }
    })
    //   2.拖动 cutBox
    $('#cutBox').mousedown(function (e) {
        let downEvent = e
        let divLeft = parseInt($(this).css('left'));
        let divTop = parseInt($(this).css('top'));
        $(this).mousemove(function (event) {
            // this的改变css
            let moveEvent = event
            // console.log(moveEvent.clientX - divLeft)
            // console.log(moveEvent.clientY - divTop)
            $(this).css({
                left:moveEvent.clientX - downEvent.clientX + divLeft+'px',
                top:moveEvent.clientY - downEvent.clientY + divTop+"px"
            })
        })
    })
    $('#cutBox').mouseup(function () {
        //   3将cutbox的图案渲染在newcanvas  什么时候渲染
        $('#cutBox').off('mousemove')
        let x =parseInt($(this).css('left'))
        let y =parseInt($(this).css('top'))
        // console.log(parseInt($(this).css('top')))
        // console.log(parseInt($(this).css('left')))
        // 3.2拿到区域内的图片
        // $("#myCanvas")[0].getImageData(起始X,起始Y,宽,高)
        let imgData = ctx.getImageData(x,y,150,150)
        // 3.3 将获取的装到新canvas里面
        newCtx.putImageData(imgData,0,0)
    })

    //   上传 newcanvas里面的图片
    $('#uploadBtn').click(function () {
        // console.log($('#newCanvas')[0].toDataURL())
        let imgUrl = $('#newCanvas')[0].toDataURL()
        $.ajax({
            url:'/uplaodImageTouXiang',
            type:'post',
            data:{imgUrl},
            success(data){
                console.log(data)
                $('#myimg')[0].src = data.data
            }
        })
    })
</script>
</body>
</html>